<template>
  <div class="loginMain">

    <div class="main_left">
      <img class="logo" alt="logo_float" src="~@/assets/logo_login.png">
      <!-- <div class="welcome">
        <h1>欢迎登录</h1>
        <p>云车场管理系统平台端</p>
        <div class="line"></div>
      </div> -->
    </div>
    <div class="right_form">
      <a-form :form="form" ref="formLogin" id="formLogin" class="formLogin">
        <div class="form_header">人行管理系统</div>
        <div class="line"></div>
        <div class="username_password_login">用户名密码登录</div>
        <a-form-item>
          <a-input v-decorator="['username',validatorRules.username,{ validator: this.handleUsernameOrEmail }]"
            type="text" class="username" placeholder="用户名">
            <a-icon class="user-icon" slot="prefix" type="user" :style="{ color: 'rgba(66, 122, 238, 1)'}" />
          </a-input>
        </a-form-item>

        <a-form-item>
          <a-input v-decorator="['password',validatorRules.password]" type="password" class="password"
            autocomplete="false" placeholder="密码">
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(66, 122, 238, 1)' }" />
          </a-input>
        </a-form-item>

        <a-row :gutter="0">
          <a-col :span="14">
            <a-form-item>
              <a-input v-decorator="['inputCode',validatorRules.inputCode]" type="text" class="test"
                placeholder="请输入验证码">
                <a-icon slot="prefix" v-if="verifiedCodess===inputCode" type="smile"
                  :style="{ color: 'rgba(66, 122, 238, 1)' }" />
                <a-icon slot="prefix" v-else type="frown" :style="{ color: 'rgba(66, 122, 238, 1)' }" />
              </a-input>
            </a-form-item>
          </a-col>

          <a-col :span="10">
            <img alt="如果看不清楚，请单击图片刷新！" class="codeImg" :src="captchaSrc" @click="refreshCode" />
          </a-col>

        </a-row>

        <a-form-item>
          <a-checkbox v-model="formLogin.rememberMe">自动登录</a-checkbox>
        </a-form-item>

        <a-form-item style="margin-top:2rem;">
          <a-button type="primary" htmlType="submit" class="login_button" :loading="loginBtn"
            @click.stop.prevent="handleSubmit" :disabled="loginBtn">登录
          </a-button>
        </a-form-item>

      </a-form>
      <div class="foot">Copyright © 金豆豆互联网有限责任公司技术支持</div>
    </div>

  </div>
</template>

<script>
  import TwoStepCaptcha from '@comp/tools/TwoStepCaptcha'
  import {
    mapActions
  } from 'vuex'
  import {
    timeFix
  } from '@/utils/util'
  import Vue from 'vue'
  import {
    ACCESS_TOKEN,
    ENCRYPTED_STRING
  } from '@/store/mutation-types'
  import JGraphicCode from '@comp/jeecg/JGraphicCode'
  import {
    putAction
  } from '@api/manage'
  import {
    postAction
  } from '@api/manage'
  import {
    encryption,
    getEncryptedString
  } from '@/utils/encryption/aesEncrypt'

  export default {
    components: {
      TwoStepCaptcha,
      JGraphicCode
    },
    data() {
      return {
        src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
        customActiveKey: 'tab1',
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        requiredTwoStepCaptcha: false,
        stepCaptchaVisible: false,
        form: this.$form.createForm(this),
        encryptedString: {
          key: '',
          iv: ''
        },
        state: {
          time: 60,
          smsSendBtn: false
        },
        formLogin: {
          username: '',
          password: '',
          captcha: '',
          mobile: '',
          rememberMe: true
        },
        validatorRules: {
          username: {
            rules: [{
              required: true,
              message: '请输入用户名!',
              validator: 'click'
            }]
          },
          password: {
            rules: [{
              required: true,
              message: '请输入密码!',
              validator: 'click'
            }]
          },
          mobile: {
            rules: [{
              validator: this.validateMobile
            }]
          },
          captcha: {
            rule: [{
              required: true,
              message: '请输入验证码!'
            }]
          },
          inputCode: {
            rules: [{
              required: true,
              message: '请输入验证码!'
            }, {
              validator: this.validateInputCode
            }]
          }
        },
        verifiedCode: '',
        inputCode:'',
        departList: [],
        departVisible: false,
        departSelected: '',
        currentUsername: '',
        validate_status: '',
        captchaSrc: '',
        verifiedCodess:''
      }
    },
    created() {
      Vue.ls.remove(ACCESS_TOKEN)
      this.getRouterData()
      this.getEncrypte()
      this.refreshCode();
      // update-begin- --- author:scott ------ date:20190225 ---- for:暂时注释，未实现登录验证码功能
      //      this.$http.get('/auth/2step-code')
      //        .then(res => {
      //          this.requiredTwoStepCaptcha = res.result.stepCode
      //        }).catch(err => {
      //          console.log('2step-code:', err)
      //        })
      // update-end- --- author:scott ------ date:20190225 ---- for:暂时注释，未实现登录验证码功能
      // this.requiredTwoStepCaptcha = true
    },
    methods: {
      ...mapActions(['Login', 'Logout', 'PhoneLogin']),
      // handler
      handleUsernameOrEmail(rule, value, callback) {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
        if (regex.test(value)) {
          this.loginType = 0
        } else {
          this.loginType = 1
        }
        callback()
      },
      handleTabClick(key) {
        this.customActiveKey = key
        // this.form.resetFields()
      },
      handleSubmit() {
        let that = this
        let loginParams = {
          remember_me: that.formLogin.rememberMe
        }
        that.loginBtn = true
        // 使用账户密码登陆
        if (that.customActiveKey === 'tab1') {
          that.form.validateFields(['username', 'password', 'inputCode'], {
            force: true
          }, (err, values) => {
            if (!err) {
              loginParams.username = values.username
              // loginParams.password = values.password
              loginParams.captcha = values.inputCode
              let encryptStr = encryption(values.password, that.encryptedString.key, that.encryptedString.iv)
              loginParams.password = encodeURI(encryptStr)
              that
                .Login(loginParams)
                .then(res => {
                  // this.departConfirm(res)
                  this.loginSuccess()
                })
                .catch(err => {
                  that.requestFailed(err)
                })
            } else {
              that.loginBtn = false
            }
          })
        }
      },

      stepCaptchaSuccess() {
        this.loginSuccess()
      },
      stepCaptchaCancel() {
        this.Logout().then(() => {
          this.loginBtn = false
          this.stepCaptchaVisible = false
        })
      },
      loginSuccess() {
        this.loginBtn = false
        this.$router.push({
          name: 'dashboard'
        })
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      },
      cmsFailed(err) {
        this.$notification['error']({
          message: '登录失败',
          description: err,
          duration: 4
        })
      },
      requestFailed(err) {
        this.$notification['error']({
          message: '登录失败',
          description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
          duration: 4
        })
        this.loginBtn = false
      },
      validateMobile(rule, value, callback) {
        if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
          callback()
        } else {
          callback('您的手机号码格式不正确!')
        }
      },
      validateInputCode(rule, value, callback) {
        this.inputCode = value;
        if (!value || this.verifiedCodess == this.inputCode) {
          callback()
        } else {
          callback('您输入的验证码不正确!')
        }
        // callback()
      },
      departConfirm(res) {
        if (res.success) {
          let multi_depart = res.result.multi_depart
          //0:无部门 1:一个部门 2:多个部门
          if (multi_depart == 0) {
            this.loginSuccess()
            // this.$notification.warn({
            //   message: '提示',
            //   description: `您尚未归属部门,请确认账号信息`,
            //   duration:3
            // });
          } else if (multi_depart == 2) {
            this.departVisible = true
            this.currentUsername = this.form.getFieldValue('username')
            this.departList = res.result.departs
          } else {
            this.loginSuccess()
          }
        } else {
          this.requestFailed(res)
          this.Logout()
        }
      },
      departOk() {
        if (!this.departSelected) {
          this.validate_status = 'error'
          return false
        }
        let obj = {
          orgCode: this.departSelected,
          username: this.form.getFieldValue('username')
        }
        putAction('/sys/selectDepart', obj).then(res => {
          if (res.success) {
            this.departClear()
            this.loginSuccess()
          } else {
            this.requestFailed(res)
            this.Logout().then(() => {
              this.departClear()
            })
          }
        })
      },
      departClear() {
        this.departList = []
        this.departSelected = ''
        this.currentUsername = ''
        this.departVisible = false
        this.validate_status = ''
      },
      departChange(value) {
        this.validate_status = 'success'
        this.departSelected = value
      },
      getRouterData() {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            username: this.$route.params.username
          })
        })
      },
      //强制获取密码加密规则
      getEncrypte() {
        // var encryptedString = Vue.ls.get(ENCRYPTED_STRING)
        // if (encryptedString == null) {
        getEncryptedString().then(data => {
          this.encryptedString = data
        })
        // } else {
        // this.encryptedString = encryptedString
        // console.log(encryptedString, 'this.encryptedString')
        // }
      },
      refreshCode: function () {
        postAction('/sys/captcha').then(res => {
          if (res.success) {
            this.captchaSrc = res.result.image;
            this.verifiedCodess = res.result.text;
          }
        })
      }
    }
  }
</script>

<style>
  html {
    font-size: 20px;
  }

  @media screen and (max-width: 1680px) {
    html {
      font-size: 16px;
    }
  }

  @media screen and (max-width: 1440px) {
    html {
      font-size: 14px;
    }
  }

  @media screen and (max-width: 1080px) {
    html {
      font-size: 12px;
    }
  }

  @media screen and (max-width: 960px) {
    html {
      font-size: 10px;
    }
  }

  @media screen and (max-width: 768px) {
    html {
      font-size: 8px;
    }
  }

  .loginMain {
    display: flex;
    font-family: MicrosoftYaHei;
    height: 100%;
  }

  .main_left {
    width: 60%;
    height: 100%;
    background: url('~@assets/login01.png') no-repeat center center;
    background-size: 60% 60%;
    position: relative;
  }

  .loginMain .logo {
    margin: 4rem 5rem;
    width: 8rem;
    height: 2.5rem;
  }

  .welcome {
    color: #fff;
    position: absolute;
    bottom: 10rem;
    left: 7.5rem;

  }

  .welcome p {
    font-size: 1.7rem;
    letter-spacing: 3px;
    margin: 0 0 1rem;
    font-weight: 100;
  }

  .welcome h1 {
    color: #fff;
    font-size: 4.5rem;
    letter-spacing: 8px;
    line-height: 6rem;
    font-weight: 100;
    margin: 0;
  }

  .welcome .line {
    width: 7em;
    font-size: 1.7rem;
    height: 4px;
    background-color: #fff;
  }

  .loginMain .right_form {
    width: 40%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    position: relative;
  }

  .loginMain .formLogin {
    width: 23rem;
    margin: auto;
  }

  .formLogin .ant-form-item {
    margin-bottom: 1.02rem;
  }

  .formLogin .ant-form-item-control {
    line-height: 2rem;
  }

  .loginMain .form_header {
    font-size: 1.9rem;
    color: #1F1F1F;
    letter-spacing: 3px;
    line-height: 2.5rem;
    text-align: center;
  }

  .loginMain .formLogin .line {
    width: 7.5rem;
    height: 0.2rem;
    border-radius: 1px;
    background-color: #3572E2;
    margin: 0.7rem auto 0;
  }

  .loginMain .formLogin .ant-input {
    font-size: 0.8rem;
    line-height: 1rem;
    padding-top: 1rem;
    padding-bottom: 1rem;
    height: 3rem;
  }
  .loginMain .codeImg{
    display: block;
    margin:auto;
    height:3rem;
    width:96%;
    border-radius: 4px;
  }

  .username_password_login {
    line-height: 26px;
    font-size: 1rem;
    color: #427AEE;
    margin: 2.5rem 0 1rem;
  }

  .login_button {
    width: 100%;
    height: 3rem;
    background: #427AEE;
    border-radius: 4px;
    font-size: 0.9rem;
    letter-spacing: 0.5rem;

  }

  .loginMain .foot {
    font-size: 0.6rem;
    color: #333333;
    letter-spacing: 1px;
    text-align: center;
    position: absolute;
    bottom: 2.5rem;
    text-align: center;
  }
</style>